﻿using System.Linq;
using System.Threading.Tasks;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.MultiTenancy;
using Abp.Runtime.Security;
using Lpb.BookList.Authorization.Roles;
using Lpb.BookList.Authorization.Users;
using Lpb.BookList.Editions;
using Lpb.BookList.MultiTenancy.Dto;
using Microsoft.AspNetCore.Identity;

namespace Lpb.BookList.MultiTenancy
{
    public class TenantRegistrationAppService : BookListAppServiceBase, ITenantRegistrationAppService
    {

        private readonly EditionManager _editionManager;
        private readonly RoleManager _roleManager;
        private readonly IAbpZeroDbMigrator _abpZeroDbMigrator;
        private readonly IPasswordHasher<User> _passwordHasher;

        public TenantRegistrationAppService(EditionManager editionManager, RoleManager roleManager, IAbpZeroDbMigrator abpZeroDbMigrator, IPasswordHasher<User> passwordHasher)
        {
            _editionManager = editionManager;
            _roleManager = roleManager;
            _abpZeroDbMigrator = abpZeroDbMigrator;
            _passwordHasher = passwordHasher;
        }


        public async Task<TenantDto> RegisterTenantAsync(CreateTenantDto input)
        {

            var tenant = new Tenant(input.TenancyName, input.Name)
            {
                IsActive = true,
                ConnectionString = input.ConnectionString.IsNullOrEmpty()
                    ? null
                    : SimpleStringCipher.Instance.Encrypt(input.ConnectionString)
            };
            //连接字符串要进行加密

            var defaultEdition = await _editionManager.FindByNameAsync(EditionManager.DefaultEditionName);
            if (defaultEdition != null)
            {
                tenant.EditionId = defaultEdition.Id;
            }
            // 创建租户信息
            await TenantManager.CreateAsync(tenant);
            await CurrentUnitOfWork.SaveChangesAsync();
            // 初始化数据信息迁移
            _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);

            // 所以设置当前的工作单元为新注册登录的租户信息
            using (CurrentUnitOfWork.SetTenantId(tenant.Id))
            {
                CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));
                // role =admin  permission  user 

                await CurrentUnitOfWork.SaveChangesAsync();

                var adminRole = _roleManager.Roles.Single(a => a.Name == StaticRoleNames.Tenants.Admin);

                await _roleManager.GrantAllPermissionsAsync(adminRole);
                //创建admin用户信息

                var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress);

                //密码为空时，提供默认密码
                adminUser.Password = _passwordHasher.HashPassword(adminUser, input.Password.IsNullOrWhiteSpace() ? User.DefaultPassword : input.Password);

                CheckErrors(await UserManager.CreateAsync(adminUser));

                await CurrentUnitOfWork.SaveChangesAsync();

                CheckErrors(await UserManager.AddToRoleAsync(adminUser, adminRole.Name));
                await CurrentUnitOfWork.SaveChangesAsync();

            }

            return tenant.MapTo<TenantDto>();


        }







    }
}